Page({
    data: {
        list:[],
        checkedAddress: {
            name: '请选择收货地址',
            tel: '',
            addressDetail: ''
        },
        checkedGoodsList: [],
        money: [],
        productIds: '',
        addressId: 0,
        value: ''
    },

    // 结算页 getCheckoutData 函数（修改后）
    getCheckoutData(productIds) {
        const token = wx.getStorageSync('token');
        wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/cart/checkout',
            data: {
                cartId: 0,
                addressId: this.data.addressId || 0, 
                couponId: 0,
                userCouponId: 0,
                grouponRulesId: 0,
                productIds: productIds.join(',') // 关键：传递选中的商品ID
            },
            method: "GET",
            header: {
                'x-byesame-token': token,
            },
            success: (res) => {
                console.log("结算页面", res);
                if (res.data.errno === 0) {
                    const data = res.data.data;
                    this.setData({
                        checkedAddress: data.checkedAddress || this.data.checkedAddress,
                        checkedGoodsList: data.checkedGoodsList || [], // 选中商品列表
                        list:res.data.data,
                        money: {
                            goodsTotalPrice: this.formatPrice(data.goodsTotalPrice || 0),
                            freightPrice: this.formatPrice(data.freightPrice || 0),
                            couponPrice: this.formatPrice(data.couponPrice || 0)
                        }
                    });
                } else {
                    wx.showToast({
                        title: res.data.errmsg,
                        icon: 'error'
                    });
                }
            },
            fail: (err) => {
                console.error('结算接口请求失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'error'
                });
            }
        });
    },

   formatPrice(price) {
        return parseFloat(price).toFixed(2);
    },
    // 选择地址
    address() {
        wx.navigateTo({
            url: '/pages/address/address',
        })
    },

    // 订单备注变化
    onChange(event) {
        this.setData({
            value: event.detail
        });
    },

    onLoad(options) {
        const productIds = options.productIds ? options.productIds.split(',').map(id => parseInt(id)) : [];
        console.log('接收到的商品ID:', productIds);

        this.setData({
            productIds: productIds.join(',')
        });

        // 获取结算数据
        this.getCheckoutData(productIds);
    },

    onShow() {
        // 如果从地址页返回时addressId已更新（非初始值0），重新获取结算数据
        if (this.data.addressId !== 0) {
          const productIds = this.data.productIds.split(',').map(id => parseInt(id));
          this.getCheckoutData(productIds);
        }
      },
})